package xdpm.nhom16.GUI;

import java.util.ArrayList;

import android.view.View.OnClickListener;
import xdpm.nhom16.R;
import xdpm.nhom16.BUS.DataProvider;
import xdpm.nhom16.BUS.SearchEngine;
import xdpm.nhom16.DTO.DuLieuSearchDTO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.SharedPreferences;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

public class DanhSachKetQua extends Activity
{
	/** Called when the activity is first created. */
	private ListView danhSach;
	private AutoCompleteTextView txtSearch;
	private ImageButton imageButtonSearch;
	private ArrayList<DuLieuSearchDTO> lstSearch;
	private int NUM_PER_PAGE = 20;
	private int startIndex = 0;
	private int sizeOfLstduLieuTho;
	private SearchEngine searchEng;
	private int typeSort;
	private int typeOrder;
	
	SharedPreferences sharedPrefs;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		
		searchEng = new SearchEngine(DataProvider.getContext());
		
		setContentView(R.layout.danh_sach);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title_search);
		setContentView(R.layout.danh_sach);

		
		txtSearch = (AutoCompleteTextView) findViewById(R.id.edittextQuerySearch);
		imageButtonSearch = (ImageButton) findViewById(R.id.imageButtonSearch);
		imageButtonSearch.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0)
			{
				// TODO Auto-generated method stub
				onClickSearchButton();
			}
		});

		danhSach = (ListView) findViewById(R.id.list);

		Bundle mBundle = new Bundle();
		mBundle = getIntent().getExtras();
		String query = mBundle.getString("SearchQuery");

		
		Autocomplete auto = new Autocomplete(txtSearch, searchEng, this);
		auto.test();
		
		
		
		txtSearch.setText(query);
		lstSearch = searchEng.search(query);
		startIndex = 0;
		sizeOfLstduLieuTho = lstSearch.size();

		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		if (isSettingShowTip())
		{
			onTip();
		}
		
		if (isSettingSort())
		{
			typeSort = getDefaultSettingTypeSort();
			typeOrder = getDefaultSortMethod();
			
			sortData(typeSort);
		}
		else	{
			setAdapter();
		}
	}

	public void onTip()
	{
		AlertDialog.Builder alertDialog = new Builder(this);
		alertDialog.create();
		alertDialog.setTitle("Hướng dẫn");
		alertDialog.setIcon(R.drawable.tip);

		final View tipView = getLayoutInflater().inflate(R.layout.huong_dan, null);

		alertDialog.setView(tipView);

		CheckBox chkShowTip = (CheckBox) tipView.findViewById(R.id.chkShowTip);
		chkShowTip.setChecked(isSettingShowTip());

		chkShowTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				setSettingShowTip(isChecked);
			}
		});

		alertDialog.setPositiveButton("Đóng", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which)
			{

			}
		});

		alertDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.add(1, 1, 1, "Trước");
		menu.add(1, 2, 2, "Sắp xếp");
		menu.add(1, 3, 3, "Sau");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{

		switch (item.getItemId())
		{
		case 1:
			if (startIndex == 0)
			{
				Toast.makeText(this, "Bạn đang ở trang đầu tiên", Toast.LENGTH_LONG).show();
			}
			else
			{
				startIndex -= NUM_PER_PAGE;
				setAdapter();
				Log.e("GETDTO", "Back page");
			}
			break;
		case 3:
			if (startIndex + NUM_PER_PAGE >= sizeOfLstduLieuTho)
			{
				Toast.makeText(this, "Bạn đang ở trang cuối cùng", Toast.LENGTH_LONG).show();
			}
			else
			{
				startIndex += NUM_PER_PAGE;
				setAdapter();
				Log.e("GETDTO", "Next page");
			}
			break;
		case 2:
			AlertDialog.Builder alertDialog = new Builder(this);
			alertDialog.create();
			alertDialog.setTitle("Sắp xếp");
			alertDialog.setIcon(R.drawable.sort);

			final View sapXepView = getLayoutInflater().inflate(R.layout.sap_xep, null);
			Spinner spinner = (Spinner) sapXepView.findViewById(R.id.spinnerLoaiSapXep);
			ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.loaisapxep_array, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner.setAdapter(adapter);

			typeOrder = 0; /* 0 => Tăng dần, 1=> Giảm dần */
			final RadioButton rdOptionTang = (RadioButton) sapXepView.findViewById(R.id.radioSapXepTang);
			final RadioButton rdOptionGiam = (RadioButton) sapXepView.findViewById(R.id.radioSapXepGiam);

			RadioButton.OnClickListener myOptionOnClickListener = new RadioButton.OnClickListener() {
				public void onClick(View arg0)
				{
					// TODO Auto-generated method stub
					if (rdOptionTang.isChecked())
					{
						typeOrder = 0;
					}
					else
					{
						typeOrder = 1;
					}
				}

			};
			rdOptionTang.setOnClickListener(myOptionOnClickListener);
			rdOptionGiam.setOnClickListener(myOptionOnClickListener);
			typeSort = 0; /* 0=> Tên dịch vụ, 1=> Tên địa điểm, 2=>Menu */

			spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

				public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
				{
					// TODO Auto-generated method stub
					typeSort = arg2;
					if (typeSort == 2){
						rdOptionTang.setText("Giá cao nhất");
						rdOptionGiam.setText("Giá thấp nhất");
					}	else	{
						rdOptionTang.setText("Tăng");
						rdOptionGiam.setText("Giảm");
					}
				}

				public void onNothingSelected(AdapterView<?> arg0)
				{
					// TODO Auto-generated method stub
				}
			});

			alertDialog.setPositiveButton("Thực hiện", new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which)
				{
					sortData(typeSort);
				}
			});
			alertDialog.setNegativeButton("Không", null);
			alertDialog.setView(sapXepView);
			alertDialog.show();
		}
		return super.onOptionsItemSelected(item);
	}

	public boolean isSettingShowTip()
	{
		return (sharedPrefs.getBoolean("perform_show_tip", true));
	}

	public void setSettingShowTip(boolean value)
	{
		SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
		prefsEditor.putBoolean("perform_show_tip", value);
		prefsEditor.commit();
	}

	// Kiểm tra giá trị có lựa chọn Sắp xếp/ Không sắp xếp trong setting
	public boolean isSettingSort()
	{
		return (sharedPrefs.getBoolean("perform_enable_sorting", true));
	}

	// Lưu trạng thái Sắp xếp/ Không sắp xếp vào setting
	public void setSettingSort(boolean value)
	{
		SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
		prefsEditor.putBoolean("perform_show_tip", value);
		prefsEditor.commit();
	}

	public int getDefaultSettingTypeSort()
	{
		String typeSort = sharedPrefs.getString("show_sorting_keyword", "");

		if (typeSort.equals("nameOfService"))
		{
			return 0;
		}

		if (typeSort.equals("nameOfPlace"))
		{
			return 1;
		}

		if (typeSort.equals("price"))
		{
			return 2;
		}

		return -1;
	}

	public void setDefaultTypeSort(int sort)
	{
		SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
		prefsEditor.putBoolean("perform_enable_sorting", true);

		switch (sort)
		{
		case 0:
			prefsEditor.putString("show_sorting_keyword", "nameOfService");
			break;

		case 1:
			prefsEditor.putString("show_sorting_keyword", "nameOfPlace");
			break;

		case 2:
			prefsEditor.putString("show_sorting_keyword", "price");
			break;
		}

		prefsEditor.commit();
	}

	public void setDefaultSortMethod(int method)
	{
		SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
		prefsEditor.putBoolean("perform_enable_sorting", true);

		switch (method)
		{
		case 0:
			prefsEditor.putString("show_sorting_method", "ascending");
			break;
			
		case 1:
			prefsEditor.putString("show_sorting_method", "descending");
			break;
		}

		prefsEditor.commit();
	}

	public int getDefaultSortMethod()
	{
		String typeSort = sharedPrefs.getString("show_sorting_method", "");

		if (typeSort.equals("ascending"))
		{
			return 0;
		}

		if (typeSort.equals("descending"))
		{
			return 1;
		}

		return -1;
	}
	
	private void sortData(int type)
	{
		if (type == 0)
		{// Tên dịch vụ
			lstSearch = searchEng.sortByTenDichVu(lstSearch, typeOrder);
		}
		else
			if (type == 1)
			{ // Tên địa điểm
				lstSearch = searchEng.sortByTenDiaDiem(lstSearch, typeOrder);
			}
			else
				if (type == 2)
				{ // Menu
					lstSearch = searchEng.sortByGiaTien(lstSearch, typeOrder);
				}
		setAdapter();
	}

	public void setAdapter()
	{
		ArrayList<PhanTu> lstPhanTu = searchEng.reference(lstSearch, startIndex, startIndex + NUM_PER_PAGE - 1);
		PhanTuAdapter adapter = new PhanTuAdapter(this, lstPhanTu, null);
		if (adapter != null)
		{

			danhSach.setAdapter(adapter);
			danhSach.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> av, View v, int i, long l)
				{
					try
					{
						Bundle bundle = new Bundle();
						bundle.putInt("Du lieu", lstSearch.get(i + startIndex).getMaDuLieu());
						Intent intent = new Intent(DanhSachKetQua.this, ChiTietDiaDiemActivity.class);
						intent.putExtras(bundle);
						startActivityForResult(intent, 0);
					}
					catch (Exception e)
					{
						System.out.println("Cannot get the selected index");
					}
				}
			});
		}
	}

	public void onClickSearchButton()
	{
		String query = txtSearch.getText().toString();
		lstSearch = searchEng.search(query);
		sizeOfLstduLieuTho = lstSearch.size();
		startIndex = 0;
		setAdapter();
	}
}